package xmlPackage;

import graphIndexerPackage.IndexerProgress;

import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.Toolkit;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.border.BevelBorder;

public class GraphicFlush implements IndexerProgress {
	
	private JFrame			parent;
	private JPanel			mainPanel;
	private LayoutManager	layout;
	private JProgressBar	progressBarGlobal;
	private JProgressBar	progressBarCurrent;
	
	private int precPhase;

	public GraphicFlush() {
		parent				= new JFrame("Indexer");
		mainPanel			= new JPanel();
		layout				= new BoxLayout(mainPanel, BoxLayout.Y_AXIS);
		progressBarGlobal	= new JProgressBar();
		progressBarCurrent	= new JProgressBar();
		
		progressBarGlobal.setPreferredSize(new Dimension(200,27));
		progressBarGlobal.setPreferredSize(new Dimension(200,27));
		
		mainPanel.add( progressBarCurrent );
		mainPanel.add( progressBarGlobal );
		
		mainPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED), "Saving:"));
		
		mainPanel.setLayout(layout);
		//parent.setSize(new Dimension(200, ));
		parent.setAlwaysOnTop(true);
	
		int posX = Toolkit.getDefaultToolkit().getScreenSize().width / 2 - 100;
		int posY = Toolkit.getDefaultToolkit().getScreenSize().height / 2 - 15;
		parent.setLocation(posX, posY);
		
		parent.setUndecorated(true);
		parent.setContentPane(mainPanel);
		parent.pack();
		start();
	}
	
	public void progress( int phase, int maxphase, int current, int maxcurrent) {
		if ( phase == 0 ) {
			progressBarGlobal.setIndeterminate(true);
			progressBarCurrent.setIndeterminate(true);
			progressBarGlobal.setMaximum(maxphase);
			progressBarGlobal.setMinimum(0);
			progressBarCurrent.setMinimum(0);
			precPhase = phase;
		} else {
			if ( phase == 1 ) {
				progressBarGlobal.setIndeterminate(false);
				progressBarCurrent.setIndeterminate(false);
			}
			if ( precPhase != phase ) {
				progressBarCurrent.setMaximum(maxcurrent);
				progressBarCurrent.repaint();
				precPhase = phase;
			}
			progressBarCurrent.setValue(current);
			progressBarCurrent.setString("Current "+(int)(progressBarCurrent.getPercentComplete()*100)+"%");
			progressBarGlobal.setValue(phase);
			progressBarGlobal.setString("Global "+phase +"/" + maxphase);
		}
	}

	public void start() {
		progressBarGlobal.setIndeterminate(true);
		progressBarGlobal.setStringPainted(true);
		progressBarCurrent.setIndeterminate(true);
		progressBarCurrent.setStringPainted(true);

		parent.setCursor(new Cursor(Cursor.WAIT_CURSOR));
		parent.setVisible(true);
	}

	public void progressFinish() {
		parent.setVisible(false);
		parent.dispose();
	}
}
